package com.qzsoft.zhjd.collect.modules.disconnectInfo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qzsoft.zhjd.collect.modules.disconnectInfo.entity.NSiteDisconnectRecordEntity;
import com.qzsoft.zhjd.collect.modules.disconnectInfo.mapper.NSiteDisconnectRecordMapper;
import com.qzsoft.zhjd.collect.modules.disconnectInfo.service.NSiteDisconnectRecordService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


@Service("nSiteDisconnectRecordService")
public class NSiteDisconnectRecordServiceImpl extends ServiceImpl<NSiteDisconnectRecordMapper, NSiteDisconnectRecordEntity> implements NSiteDisconnectRecordService {

    @Autowired
    private NSiteDisconnectRecordMapper nSiteDisconnectRecordMapper;
    @Override
    @Transactional
    public String saveDataUpload(JSONArray jsonArray){
        JSONObject data = (JSONObject)JSON.toJSON(jsonArray.get(0));
        //按数据组进行数据批量插入
        List<NSiteDisconnectRecordEntity> insertList = new ArrayList<>();
        //获取最后一次收到心跳的时间
        QueryWrapper<NSiteDisconnectRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id",data.getString("groupId"));
        queryWrapper.eq("send",-1);
        queryWrapper.eq("group_no",1);
        NSiteDisconnectRecordEntity onlineEntity = this.getOne(queryWrapper);
        Date lastOnlineTime = null;
        if(onlineEntity!=null){
            lastOnlineTime = onlineEntity.getCreateDate();
        }
        for (Object object : jsonArray) {
            JSONObject recordObj = (JSONObject) JSON.toJSON(object);
            NSiteDisconnectRecordEntity entity = new NSiteDisconnectRecordEntity();
            //采集设备终端编号
            entity.setType(recordObj.getString("type"));
            //数据抽取源表主键
            entity.setSourceId(recordObj.getInteger("iD"));
            //组编号(32位UUID)
            entity.setGroupId(recordObj.getString("groupId"));
            //组序号
            entity.setGroupNo(recordObj.getInteger("groupNo"));
            //开机时间
            entity.setBootTime(recordObj.getDate("bootTime"));
            //断网开始时间
            entity.setDisconnectBegin(recordObj.getDate("disconnectBegin"));
            //断网结束时间
            entity.setDisconnectEnd(recordObj.getDate("disconnectEnd"));
            //断网时长(分钟)
            entity.setDisconnectDuration(recordObj.getInteger("disconnectDuration"));
            //关机时间
            entity.setUnattendedTime(recordObj.getDate("unattendedTime"));
            //0：已完成记录；-1：开机运行时记录
            entity.setSend(recordObj.getInteger("send"));
            //是否正常关机：YES;NO
            entity.setIsNormalShutdown(recordObj.getString("isNormalShutdown"));
            //采集创建时间
            entity.setCreateDate(new Date());
            //采集数据类型
            entity.setSiteType(recordObj.getString("siteType"));
            //若采集数据无关机时间，则取在线数据中最后一次在网时间作为关机时间
            if(entity.getUnattendedTime()==null&&lastOnlineTime!=null){
                entity.setUnattendedTime(lastOnlineTime);
            }
            //过滤关机后产生的垃圾数据
            if(entity.getIsNormalShutdown()!=null){
                //存入数列
                insertList.add(entity);
            }
        }
        //清除在线数据
        remove(Wrappers.<NSiteDisconnectRecordEntity>query().lambda().eq(NSiteDisconnectRecordEntity::getGroupId, data.getString("groupId")).eq(NSiteDisconnectRecordEntity::getSend,-1));
        boolean flag =this.saveBatch(insertList);
        if(flag){
            return "HAS_INSERT";
        }
        return "FAILURE_INSERT";
    }

    @Override
    @Transactional
    public String onlineDataUpload(JSONObject jsonObject) {
        String hasRecord = jsonObject.getString("hasRecord");
        String groupId = jsonObject.getString("groupId");
        if("YES".equals(hasRecord)){
            //若出现断网记录或初始化开机记录则进行数据全量同步
            List<NSiteDisconnectRecordEntity> insertList = new ArrayList<>();
            //全量同步数据清除
            remove(Wrappers.<NSiteDisconnectRecordEntity>query().lambda().eq(NSiteDisconnectRecordEntity::getGroupId, groupId).eq(NSiteDisconnectRecordEntity::getSend,-1));
            //全量同步数据插入
            JSONArray onlineList = jsonObject.getJSONArray("onlineList");
            for (Object object : onlineList) {
                JSONObject recordObj = (JSONObject) JSON.toJSON(object);
                NSiteDisconnectRecordEntity entity = new NSiteDisconnectRecordEntity();
                //采集设备终端编号
                entity.setType(recordObj.getString("type"));
                //数据抽取源表主键
                entity.setSourceId(recordObj.getInteger("iD"));
                //组编号(32位UUID)
                entity.setGroupId(recordObj.getString("groupId"));
                //组序号
                entity.setGroupNo(recordObj.getInteger("groupNo"));
                //开机时间
                entity.setBootTime(recordObj.getDate("bootTime"));
                //断网开始时间
                entity.setDisconnectBegin(recordObj.getDate("disconnectBegin"));
                //断网结束时间
                entity.setDisconnectEnd(recordObj.getDate("disconnectEnd"));
                //断网时长(分钟)
                entity.setDisconnectDuration(recordObj.getInteger("disconnectDuration"));
                //0：已完成记录；-1：开机运行时记录
                entity.setSend(recordObj.getInteger("send"));
                //采集创建时间
                entity.setCreateDate(new Date());
                //采集数据类型
                entity.setSiteType(recordObj.getString("siteType"));
                //存入数列
                insertList.add(entity);
            }
            boolean flag =this.saveBatch(insertList);
            if(flag){
                return "HAS_INSERT";
            }
            return "FAILURE_INSERT";
        }else{
            //若未携带在线数据，则仅更新最后连接时间
            // 更新
            UpdateWrapper<NSiteDisconnectRecordEntity> updateWrapper = new UpdateWrapper<>();
            //修改语句
            updateWrapper.set("create_date",new Date());
            //条件
            updateWrapper.eq("group_id",groupId);
            //执行更替语句
            update(updateWrapper);
        }
        return "FAILURE_INSERT";
    }
}
